<template>
  <!-- Map 筛选控件 -->
  <view class="filter-control">
    <view class="filter-control__content">
      <view class="filter-control--top">
        <picker
          class="region-picker"
          :range="cityData"
          :value="regionValue"
          mode="multiSelector"
          range-key="extName"
          @change="regionChange"
          @columnchange="regionColumnchange"
        >
          <PickerValue :valueText="regionValueText" />
        </picker>
        <view class="search-view" @click="toContactList">
          <UniSearchBar
            placeholder="搜索"
            radius="64"
            bgColor="#F5F5F5"
            v-model="searchValue"
            readonly
            @confirm="confirm"
            @clear="clear"
            @cancel="clear"
          />
        </view>
      </view>
      <view class="filter-control--bottom">
        <view class="left">
          <picker
            class="filter-btn"
            style="margin-left: 0"
            mode="selector"
            :range="insideOutsideData"
            range-key="text"
            :value="insideOutside"
            @change="sourceTypeChange"
          >
            <PickerValue :valueText="getValueText" />
          </picker>
        </view>
        <button
          class="filter-btn"
          :class="[areaSelected.length && 'active']"
          type="none"
          @click="toAreaSelection"
        >
          <text v-if="areaSelected.length">{{ areaSelected[0].name }}</text>
          <text v-else>区域</text>

          <view class="triangle"></view>
        </button>
        <button
          v-if="insideOutside === SourceTypeEnum.INSIDE"
          class="filter-btn"
          :class="[typeSelected.length && 'active']"
          type="none"
          @click="toTypeSelection"
        >
          <text>筛选</text>
          <view class="triangle"></view>
        </button>
        <button
          v-if="insideOutside === SourceTypeEnum.INSIDE"
          class="filter-btn"
          :class="[industryIdSelected.length && 'active']"
          type="none"
          @click="selectIndustryShow = true"
        >
          <text>行业</text>
          <view class="triangle"></view>
        </button>
      </view>
    </view>
  </view>

  <SelectIndustry
    v-model:show="selectIndustryShow"
    :is-api-data="true"
    :selected="industryIdSelected"
    @submit="handleSelectIndustrySubmit"
  />
</template>

<script setup lang="ts">
  import type { ClassTypeListResult, IAreaDataResultItem } from '@/api/indexTypes';
  import type { Localdata } from '@/components/Form/types';
  import { SourceTypeEnum, ViewTypeEnum } from '@/enums/contactsEnum';
  import { navigateTo } from '@/router';
  import type { TypeSelectedItem } from '@/router/types/modules';
  import { computed, type PropType, ref, unref } from 'vue';
  import PickerValue from '@/components/Form/components/PickerValue.vue';
  import { getCityData } from '@/components/Form/utils/getCityData';
  import UniSearchBar from '@/uni_modules/uni-search-bar/components/uni-search-bar/uni-search-bar.vue';
  import { useEventBus } from '@vueuse/core';
  import { mapAreaInfoFooKey } from '../utils/fooKey';
  import { propTypes } from '@/utils/propTypes';
  import { Toast } from '@/utils';
  import { useDebounceFn } from '@/hooks/core/useDebounceFn';
  import SelectIndustry from '@/components/SelectIndustry/index.vue';

  const bus = useEventBus(mapAreaInfoFooKey);

  bus.on(async (info) => {
    if (!info) return;
    let { provinceId, cityId, cityName } = info;
    if (cityName && cityId !== regionValueId.value) {
      Toast({
        title: cityName,
        duration: 1000,
        mask: false,
      });
    }

    if (!cityData.value[0]) {
      cityData.value[0] = await getCityData();
    }
    if (!provinceId) provinceId = cityData.value[0][0].id;
    cityData.value[1] = await getCityData(provinceId);
    if (!cityId) cityId = cityData.value[1][0].id;

    const provinceIndex = cityData.value[0].findIndex((v) => v.id === provinceId);
    const cityIndex = cityData.value[1].findIndex((v) => {
      const bol = v.id === cityId;
      if (bol) {
        regionValueText.value = v.extName;
        regionValueId.value = v.id;
      }
      return bol;
    });
    getAreaData();
    regionValue.value = [provinceIndex, cityIndex];
  });

  const props = defineProps({
    viewType: Number as PropType<ViewTypeEnum>,
    distanceValue: propTypes.number.def(3000),
    assType: {
      type: Number as PropType<SourceTypeEnum>,
      required: true,
    },
  });

  const emit = defineEmits<{
    (e: 'sourceTypeChange', type: SourceTypeEnum): void;
    (e: 'filterChange', type: Recordable<(number | string)[]> | null): void;
    (e: 'arearChange', type?: IAreaDataResultItem): void;
    (e: 'searchConfirm', type: string): void;
    (
      e: 'regionChange',
      type: { provinceItem: IAreaDataResultItem; cityItem: IAreaDataResultItem },
    ): void;
  }>();


  const selectIndustryShow = ref(false);
  const searchValue = ref('');
  const cityData = ref<Array<IAreaDataResultItem[]>>([]);
  const regionValue = ref<number[]>([]);
  const regionValueText = ref('');
  const regionValueId = ref();

  /** 通过省切换市的数据 */
  async function regionColumnchange(e: any) {
    const { column, value } = e.detail as { column: number; value: number };
    if (column === 0) {
      const pid = cityData.value[0][value].id;
      cityData.value[1] = await getCityData(pid);
    }
  }

  /** 选择省市 */
  function regionChange(e: any) {
    const values = e.detail.value as number[];
    const provinceItem = cityData.value[0][values[0]];
    const cityItem = cityData.value[1][values[1]];
    regionValueText.value = cityItem.extName;
    regionValueId.value = cityItem.id;
    getAreaData();
    const item = localData.value[0];
    areaSelected.value = [
      {
        key: item.key,
        id: item.list[0].id,
        name: item.list[0].name,
      },
    ];
    emit('regionChange', {
      provinceItem,
      cityItem,
    });
  }

  const areaDataRef = ref<IAreaDataResultItem[]>([]);
  async function getAreaData() {
    const areaData = await getCityData(regionValueId.value);
    areaDataRef.value = areaData;
    localData.value[0] = {
      key: 'areaId',
      list: [{ id: 'all', name: '不限' }, ...areaData.map((v) => ({ id: v.id, name: v.extName }))],
      name: '区域',
    };
  }

  function confirm(e: any) {
    emit('searchConfirm', e.value);
  }

  function clear() {
    emit('searchConfirm', '');
  }

  const insideOutside = ref(props.assType);

  const insideOutsideData = ref<Localdata[]>([
    {
      value: SourceTypeEnum.ALL,
      text: '全部',
    },
    {
      value: SourceTypeEnum.INSIDE,
      text: '会内人脉',
    },
    {
      value: SourceTypeEnum.OUTSIDE,
      text: '会外人脉',
    },
  ]);

  const getValueText = computed(() => unref(insideOutsideData)[unref(insideOutside)].text);

  const sourceTypeChange = (e: any) => {
    const val = Number(e.detail.value) as SourceTypeEnum;
    insideOutside.value = val;
    typeSelected.value = [];
    industryIdSelected.value = []
    emit('sourceTypeChange', val);
  };

  const typeSelected = ref<TypeSelectedItem[]>([]);
  const toTypeSelection = useDebounceFn(() => {
    navigateTo({
      name: 'typeSelection',
      options: {
        keys: ['memberLevel', 'typeId'],
        selected: unref(typeSelected),
        success: (arr) => {
          typeSelected.value = arr;
          handleFilterChange()
        },
      },
    });
  });

  const industryIdSelected = ref<number[]>([]);
  function handleSelectIndustrySubmit(ids: number[]) {
    industryIdSelected.value = ids;
    handleFilterChange();
  }

  function handleFilterChange() {
    const nArr = selectedReduce(typeSelected.value);
    emit('filterChange', { ...nArr, industryId: industryIdSelected.value });
  }


  const localData = ref<ClassTypeListResult[]>([]);
  const areaSelected = ref<TypeSelectedItem[]>([]);
  const toAreaSelection = useDebounceFn(async () => {
    navigateTo({
      name: 'typeSelection',
      options: {
        localData: unref(localData),
        selected: unref(areaSelected),
        isRadio: true,
        success: (arr) => {
          areaSelected.value = arr;
          const item = areaDataRef.value.find((v) => v.id === arr[0].id);
          emit('arearChange', item);
        },
      },
    });
  });

  function selectedReduce(arr: TypeSelectedItem[]) {
    return arr.reduce((result, val) => {
      (result[val.key] || (result[val.key] = [])).push(val.id);
      return result;
    }, {} as Recordable);
  }

  const toContactList = useDebounceFn(() => {
    navigateTo({ name: 'contactList' })
  })

  defineExpose({
    reset: () => {
      areaSelected.value = [];
    },
  });
</script>

<style scoped lang="scss">
  .filter-control {
    position: absolute;
    left: 0;
    top: 0;
    box-sizing: border-box;
    width: 100%;
    padding: 24rpx;
    z-index: 20;
    &__content {
      background-color: #fff;
      box-sizing: border-box;
      border-radius: 32rpx;
      box-shadow: 0px 4rpx 24rpx 0px rgba(150, 151, 153, 0.3);
      padding: 32rpx;
    }

    &--top {
      display: flex;
      align-items: center;
      .region-picker {
        flex-shrink: 0;
      }
      .search-view {
        flex: 1;
        margin-left: 24rpx;
      }
      .ali-icon {
        font-size: 40rpx;
        color: #999996;
      }
    }

    &--bottom {
      display: flex;
      align-items: center;
      margin-top: 24rpx;
      .left {
        flex: 1;
        display: flex;
        align-items: center;
      }

      .filter-btn {
        height: 46rpx;
        padding: 0 20rpx;
        border-radius: 10rpx;
        background-color: #f5f5f5;
        font-size: 28rpx;
        color: #000;
        line-height: 46rpx;
        margin-left: 30rpx;
        position: relative;
        .triangle {
          position: absolute;
          right: 8rpx;
          bottom: 8rpx;
          width: 0rpx;
          height: 0rpx;
          border-top: 6rpx solid transparent;
          border-right: 6rpx solid #808080;
        }

        &.active {
          background-color: #d0f7ff;
          color: #2878ff;
          .triangle {
            border-right-color: #2878ff;
          }
        }
      }
    }
  }
</style>
